package com.example.demo.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.Objects;
import java.util.UUID;

@Controller
public class FileController {
    private static final String DIR_PATH = "C:/File/";
    @GetMapping("/upload")
    public String uploadPage() {
        return "upload";
    }
    @GetMapping("/download")
    public String download(Model model) {
        File dir = new File(DIR_PATH);
        if (dir.exists() && dir.list().length > 0) {
            String[] files = dir.list();
            model.addAttribute("files", files);
        }else {
            model.addAttribute("msg", "无文件下载");
        }
        return "download";
    }
    @GetMapping("/downloadfile")
    public ResponseEntity<byte[]> downloadFile(@RequestParam("filename") String fileName) {
        File file = new File(DIR_PATH + fileName);
        try{
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(Files.readAllBytes(file.toPath()));
        }catch (IOException e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(e.getMessage().getBytes());}

    }

    @PostMapping("/upload")
    public String uploadFile(MultipartFile[] files, Model model) {
        File directory = new File(DIR_PATH);
        if (!directory.exists() && !directory.mkdirs()) {
            model.addAttribute("msg","创建目录失败，请检查服务器配置！");
            return "upload";
        }
        StringBuilder messages = new StringBuilder();
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                messages.append("请选择文件进行上传。<br>");
                continue;
            }
            String fileName = file.getOriginalFilename();
            String uniqueFileName = UUID.randomUUID()+"_" + Objects.requireNonNull(fileName);
            File destFile = new File(DIR_PATH + uniqueFileName);
            try{
                file.transferTo(destFile);
                messages.append("文件").append(fileName).append("上传成功。<br>");
            }
            catch (IOException e) {
                messages.append("文件").append(fileName).append("上传失败:").append(e.getMessage()).append("<br>");
            }

        }
        model.addAttribute("msg",messages.toString());
        return "upload";


    }
}
